package com.vcg;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.channel.ObservableConnection;
import io.reactivex.netty.client.RxClient;
import io.reactivex.netty.pipeline.PipelineConfigurator;
import org.apache.commons.codec.binary.Hex;
import rx.Subscriber;

import java.util.ArrayList;
import java.util.List;

public class Client {
    public static void main(String[] args) throws InterruptedException {
        final List<Channel> channels = new ArrayList<Channel>();
        RxClient<Object, Object> rxClient = RxNetty.newTcpClientBuilder("127.0.0.1", 3001)
                .pipelineConfigurator(pipeline -> {
                    pipeline.addLast(new SharedWashingMachineHeathDecode());
                    pipeline.addLast(new SharedWashingMachineHeathEncode());
                    pipeline.addLast(new ClientHandler());
                })
                .build();

        rxClient.connect().subscribe(new Subscriber<ObservableConnection<Object, Object>>() {
            public void onCompleted() {

            }

            public void onError(Throwable throwable) {

            }

            public void onNext(ObservableConnection<Object, Object> objectObjectObservableConnection) {
                objectObjectObservableConnection.getInput().subscribe(new Subscriber<Object>() {
                    public void onCompleted() {

                    }

                    public void onError(Throwable throwable) {

                    }

                    public void onNext(Object o) {
                        System.err.println(o.toString());
                    }
                });
                channels.add(objectObjectObservableConnection.getChannel());
            }
        });

        //伪装心跳
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        for (Channel channel : channels) {
//                            channel.writeAndFlush(Integer.parseUnsignedInt("AAH") & 0xFF);
                            channel.writeAndFlush("Haha");
                        }
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.currentThread().join();
    }
}
